<script setup>
import FormItemSearch from '@/components/form/FormItemSearch.vue'
import TableColumnIndex from '@/components/table/TableColumnIndex.vue'
import { usePagination, useRequest, useDialog } from '@/hooks'
import { deviceApi } from '@/api'
import DeviceGroupFormDialog from './DeviceGroupFormDialog.vue'
import { ElMessageBox } from 'element-plus'

const STATUS = ['删除', '正常']
const STATUS_COLORS = ['text-danger', 'text-success']

const title = computed(() => useRoute().meta.title ?? '分组列表')

const multipleSelection = ref([])

const form = ref({
  groupName: ''
})
const formRef = ref()

function reset() {
  formRef.value.resetFields()
  search()
}

const { pageSize, currentPage, pageSizes } = usePagination({
  onChange: () => refresh()
})

const { refresh, data, count } = useRequest(deviceApi.getDeviceGroupList, {
  initialData: [],
  immediate: true,
  onSuccess: result => {
    data.value = result.list
  },
  params: () => ({
    ...form.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
})

function search() {
  currentPage.value = 1
  refresh()
}

const active = ref(null)
const { visible, open } = useDialog(active)

async function handleSubmit(formValue) {
  if (active.value) {
    await deviceApi.editDeviceGroup({ ...formValue, id: active.value.id })
  } else {
    await deviceApi.addDeviceGroup(formValue)
  }
  ElMessage.success('操作成功')
  visible.value = false
  refresh()
}

function handleSelectionChange(val) {
  multipleSelection.value = val
}

async function handleRemove(ids) {
  if (!ids?.length) return ElMessage.warning('请选择要删除的设备')

  await ElMessageBox.confirm('此操作将删除选中设备, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deviceApi.delDeviceGroup({ idArray: ids.toString() })
  ElMessage.success('删除成功')
  refresh()
}
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header> {{ title }} </template>
      <el-form
        ref="formRef"
        :model="form"
        label-width="90px"
        label-suffix="："
        label-position="left"
        @submit.prevent="search"
      >
        <el-row :gutter="20">
          <FormItemSearch label="分组名称" prop="groupName">
            <el-input v-model.trim="form.groupName" clearable />
          </FormItemSearch>
        </el-row>

        <el-button type="primary" native-type="submit" @submit="search">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="open()"> 新增 </el-button>
        <el-button
          type="danger"
          @click="handleRemove(multipleSelection.map(item => item.id))"
        >
          删除
        </el-button>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <el-table
        :data="data"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <TableColumnIndex :page="currentPage" :page-size="pageSize" />
        <el-table-column prop="groupName" label="分组名称" />
        <el-table-column prop="sort" label="分组排序" />
        <el-table-column prop="status" label="分组状态">
          <template #default="{ row }">
            <span v-if="STATUS[row.status]" :class="STATUS_COLORS[row.status]">
              {{ STATUS[row.status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="groupDescribe"
          show-overflow-tooltip
          label="分组描述"
        />
        <TableColumnTime
          prop="createTime"
          show-overflow-tooltip
          label="创建时间"
        />
        <el-table-column
          prop="createUser"
          show-overflow-tooltip
          label="创建者"
        />
        <el-table-column label="操作" align="center" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="open(row)"> 编辑 </el-button>
            <el-button link type="danger" @click="handleRemove([row.id])">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        hide-on-single-page
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
        class="mt-4 justify-end"
        small
      />
    </el-card>

    <DeviceGroupFormDialog
      v-model="visible"
      :title="active ? '编辑设备分组' : '新增设备分组'"
      :detail="active"
      @submit="handleSubmit"
    />
  </div>
</template>
